package com.dragon.blelibrary.bleutils;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeAdvertiser;
import android.bluetooth.le.BluetoothLeScanner;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.util.Log;


import androidx.annotation.RequiresApi;

import com.dragon.blelibrary.BleConfig;
import com.dragon.blelibrary.events.BleEventType;
import com.dragon.blelibrary.events.BlePropertyObservable;

import java.lang.reflect.Method;
import java.util.Set;


public class BluctoothUtil {
	/**
	 * 查询已配对的设备
	 * 
	 * @param context
	 * @param mac
	 * @return
	 */
	public static BluetoothDevice getBondDevice(Context context, String mac) {
		Set<BluetoothDevice> devSet = getBluetoothManager(context).getAdapter()
				.getBondedDevices();
		for (BluetoothDevice dev : devSet) {
			if (dev != null && mac.equals(dev.getAddress())) {
				return dev;
			}
		}
		return null;
	}

	/**
	 * 获取 BluetoothManager
	 * 
	 * @param context
	 * @return
	 */
	public static BluetoothManager getBluetoothManager(Context context) {
		Context app = context.getApplicationContext();
		return (BluetoothManager) app
				.getSystemService(Context.BLUETOOTH_SERVICE);
	}

	public static BluetoothAdapter getBluetoothAdapter(Context context) {
		return getBluetoothManager(context).getAdapter();
	}

	/**
	 * 与设备解除配对
	 * 
	 * @param btDevice
	 * @return
	 * @throws Exception
	 */
	public static boolean removeBond(BluetoothDevice btDevice) throws Exception {
		Method removeBondMethod = btDevice.getClass().getMethod("removeBond");
		Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
		return returnValue.booleanValue();
	}

	/**
	 * 与设备配对
	 * 
	 * @param btDevice
	 * @return
	 * @throws Exception
	 */
	public static boolean createBond(BluetoothDevice btDevice) throws Exception {
		Method createBondMethod = btDevice.getClass().getMethod("createBond");
		Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
		return returnValue.booleanValue();
	}

	/**
	 * 重开蓝牙
	 * 
	 * @param context
	 * @param delayMillis
	 * @retrun BleEventID.BLE_OFF_ON_END
	 */
	public static void trunOffOn(final Context context, final int delayMillis) {
		final BluetoothAdapter adapter = getBluetoothAdapter(context);
		if (adapter != null) {
			adapter.disable();
			BleConfig.mHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					boolean flag = adapter.enable();
					Log.i("ble--",""+flag);
					BlePropertyObservable.getInstance().fireEvent(
							BleEventType.BLE_OFF_ON_END, null);
				}
			}, delayMillis);
		}
	}
	/**
	 * 注册监听蓝牙开关状态
	 */
	public static void registerReceiverBluctooth() {
		IntentFilter statusFilter = new IntentFilter(
				BluetoothAdapter.ACTION_STATE_CHANGED);
		BleConfig.mContext.registerReceiver(mStatusReceive, statusFilter);
	}
	/**
	 * 反注册监听蓝牙开关状态
	 */
	public static void unRegisterReceiverBluctooth(){
		BleConfig.mContext.unregisterReceiver(mStatusReceive);
	}
	private static BroadcastReceiver mStatusReceive = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction())) {
				int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
				switch (blueState) {
				case BluetoothAdapter.STATE_TURNING_ON:
					break;
				case BluetoothAdapter.STATE_ON:
					BlePropertyObservable.getInstance().fireEvent(BleEventType.BLUETOOTH_ON, null);
					break;
				case BluetoothAdapter.STATE_TURNING_OFF:
					break;
				case BluetoothAdapter.STATE_OFF:
					BlePropertyObservable.getInstance().fireEvent(BleEventType.BLUETOOTH_OFF, null);
					break;
				}
			}
		}
	};
	/**
	 * 查询ble已连接的设备
	 * @param mac
	 * @return
	 */
	@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
	public static BluetoothDevice getConnectionDevice(String mac){
		BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
		Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;//得到BluetoothAdapter的Class对象
		try {//得到连接状态的方法
			Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);
			//打开权限
			method.setAccessible(true);
			int state = (Integer) method.invoke(adapter, (Object[]) null);

//			if(state == BluetoothAdapter.STATE_CONNECTED){
				Log.i("BLUETOOTH","BluetoothAdapter.STATE_CONNECTED");
				Set<BluetoothDevice> devices = adapter.getBondedDevices();
			BluetoothLeAdvertiser list = adapter.getBluetoothLeAdvertiser();
			BluetoothLeScanner scList = adapter.getBluetoothLeScanner();
				Log.i("BLUETOOTH","devices:"+devices.size());

				for(BluetoothDevice device : devices){
					Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);
					method.setAccessible(true);
					boolean isConnected = (Boolean) isConnectedMethod.invoke(device, (Object[]) null);
					if(isConnected){
						Log.i("BLUETOOTH","connected:"+device.getName());
						if(device.getAddress().equals(mac)){
							return device;
						}
					}
				}
//			}

		} catch (Exception e) {
			Log.e("ljs","baocuol" + e.getMessage(),e);
			e.printStackTrace();
		}
		return null;
	}
}
